const log = require('../../util/log'),
    config = require('../../util/config'),
    logger = require('log4js').getLogger()

async function getTaobaoItems(obj) {
    const {
        Network,
        Page,
        DOM,
        Runtime,
        Emulation
    } = this.client;
    obj = obj || {}
    obj.times = (obj.times || 0) + 1
    if (!obj.q) {
        return new Promise(resolve => {
            resolve([])
        })
    }
    if (obj.step !== 0) {
        logger.debug('[' + __filename + ':' + __line + ']', 'getting taobao items', JSON.stringify(obj))
        obj.step = 0
    }
    // Page.navigate({
    //     url: 'https://pub.alimama.com/promo/search/index.htm?fn=search'
    // })
    // return step1_7.call(this, obj)
    Page.navigate({
        url: 'https://pub.alimama.com/promo/search/index.htm?fn=search&q=' + encodeURIComponent(obj.q) + '&_t=' + new Date().getTime()
    })
    return step3.call(this, obj)
}

async function step1_7(obj) {
    obj.times++
    if (obj.times > config.chromeMaxTimes) {
        return new Promise((resolve, reject) => {
            reject('超时')
        })
    }
    if (obj. step !== 1.7) {
        logger.debug('[' + __filename + ':' + __line + ']', 'getting taobao items step 1.7', obj.q)
        obj.step = 1.7
    }
    const {
        Network,
        Page,
        DOM,
        Runtime,
        Emulation
    } = this.client;
    var {result} = await Runtime.evaluate({expression: 'location.href'})
    if (result.value == 'https://pub.alimama.com/promo/search/index.htm?fn=search') {
        return step2.call(this, obj)
    }
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            step1_7.call(this, obj).then(result => {
                resolve(result)
            }, result => {
                reject(result)
            })
        }, 1000)
    })
}

async function step2(obj) {
    obj.times++
    if (obj.times > config.chromeMaxTimes) {
        return new Promise((resolve, reject) => {
            reject('超时')
        })
    }
    const {
        Network,
        Page,
        DOM,
        Runtime,
        Emulation
    } = this.client;
    if (obj.step !== 2) {
        logger.debug('[' + __filename + ':' + __line + ']', 'getting taobao items step 2', JSON.stringify(obj))
        obj.step = 2
    }
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".search-input")'})
    // logger.debug('[' + __filename + ':' + __line + ']', result)
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 0) {
        return new Promise(resolve => {
            setTimeout(() => {
                step2.call(this, obj).then(result => {
                    resolve(result)
                })
            }, 1000)
        })
    }
    var {result} = await Runtime.evaluate({expression: 'location.href'})
    if (result.value != 'https://pub.alimama.com/promo/search/index.htm?fn=search') {
        var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".search-input")[0].value'})
        if (result.value == obj.q) {
            return step3.call(this, obj)
        }
    }
    await Runtime.evaluate({expression: 'document.querySelectorAll(".search-input")[0].value="' + obj.q + '"'})
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".search-input")[0].value'})
    if (result.value != obj.q) {
        return new Promise(resolve => {
            setTimeout(() => {
                step2.call(this, obj).then(result => {
                    resolve(result)
                })
            }, 1000)
        })
    }
    await Runtime.evaluate({expression: 'document.querySelectorAll(".search-input")[0].click()'})
    await Runtime.evaluate({expression: 'document.querySelectorAll(".search-btn")[0].click()'})
    return new Promise(resolve => {
        setTimeout(() => {
            step2.call(this, obj).then(result => {
                resolve(result)
            })
        }, 1000)
    })
}

async function step3(obj) {
    obj.times++
    if (obj.times > config.chromeMaxTimes) {
        return new Promise((resolve, reject) => {
            // reject('超时')
            return new Promise(resolve => {
                resolve([])
            })
        })
    }
    const {
        Network,
        Page,
        DOM,
        Runtime,
        Emulation
    } = this.client;
    if (obj.step !== 3) {
        logger.debug('[' + __filename + ':' + __line + ']', 'getting taobao items step 3', JSON.stringify(obj))
        obj.step = 3
    }
    
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".pub-threenk")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 1) {
        var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".pub-threenk")[0].innerText'})
        if (result.value == '抱歉，没找到相关商品') {
            //logger.debug('[' + __filename + ':' + __line + '] here')
            return new Promise(resolve => {
                resolve([])
            })
        }
    }
    
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".pub-threenm")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 1) {
        var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".pub-threenm")[0].innerText'})
        if (result.value == '抱歉，没找到相关商品') {
            //logger.debug('[' + __filename + ':' + __line + '] here')
            return new Promise(resolve => {
                resolve([])
            })
        }
    }

    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".common-product-container")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 0) {
        //logger.debug('[' + __filename + ':' + __line + ']', 'here')
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                step3.call(this, obj).then(result => {
                    resolve(result)
                }, result => {
                    reject(result)
                })
            }, 1000)
        })
    }
    var list = []
    for (var i = 0; i < cnt; i++) {
        var prefix = 'document.querySelectorAll(".common-product-container")[' + i + '].'
        var item = {}
        // var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("a.search-box-img")[0].href'})
        // if (!/http:\/\/item.taobao.com\/item.htm\?id=\d+/.test(result.value)) {
        //     logger.debug('[' + __filename + ':' + __line + ']', '不能识别的url: ' + result.value)
        //     return new Promise(resolve => {
        //         setTimeout(() => {
        //             step3.call(this, obj).then(result => {
        //                 resolve(result)
        //             })
        //         }, 1000)
        //     })
        // }
        // item.id = result.value.substring('http://item.taobao.com/item.htm?id='.length)
        var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("img")[0].attributes["data-src"]'})
        if (result.type != 'undefined') {
            var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("img")[0].attributes["data-src"].value'})
            item.img = result.value
        } else {
            var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("img")[0].src'})
            item.img = result.value
        }
        var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("a.color-m")[0].title'})
        item.title = result.value
        var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll(".price-info-num")[0].innerText'})
        item.price = result.value
        var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll(".box-shop-info div")[1].innerText.substring(4)'})
        item.sale = result.value
        var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll(".box-shop-info div")[0].innerText'})
        item.shopName = result.value
        var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("a")[0].href'})
        item.link = result.value
        var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll(".price-info-num")[1].innerText'})
        item.rate = result.value.substring(0, result.value.length - 1)
        list.push(item)
    }
    return new Promise(resolve => {
        resolve(list)
    })
}

module.exports = getTaobaoItems
